package com.offcn.service;

import com.offcn.dao.*;
import com.offcn.entity.Course;
import com.offcn.entity.CourseUser;
import com.offcn.entity.User;
import com.offcn.utils.PageUtils;

import java.util.List;

public class CourseUserServiceImpl implements CourseUserService {
    //创建dao层对象
    CourseUserDao courseUserDao = new CourseUserDaoImpl();
    //创建userDao的对象
    UserDao userDao = new UserDaoImpl();
    //创建courseDao对象
    CourseDao courseDao = new CourseDaoImpl();
    /**
     * 分页
     *
     * @param search
     * @param currentPage
     * @param pageSize
     * @return
     */
    @Override
    public PageUtils<CourseUser> find(String search, int currentPage, int pageSize) {
        //查询总记录数
        StringBuffer sql =new StringBuffer("select cu.* from course_user as cu,user as u where cu.uid=u.uid and u.name like ?");
        List<CourseUser> list=courseUserDao.find(sql.toString(),"%"+search+"%");
        int total = list==null?0:list.size();
        //查询分页数据
        sql.append(" limit ?,?");
        List<CourseUser> courseUserList = courseUserDao.find(sql.toString(), "%" + search + "%", (currentPage - 1) * pageSize, pageSize);

        //根据每个course中的uid和cid分别查询各自表的数据，然后组装到user、course中来
        for (CourseUser courseUser : courseUserList) {
            int uid = courseUser.getUid();
            User user=userDao.findById(uid);
            courseUser.setUser(user);

            int cid = courseUser.getCid();
            Course course =courseDao.findById(cid);
            courseUser.setCourse(course);
        }

        //组装工具对象
        PageUtils<CourseUser> pageUtils = new PageUtils<>(pageSize,currentPage,total,courseUserList);
        return pageUtils;
    }

    /**
     * 修改选课信息
     *
     * @param id
     * @param cid
     * @return
     */
    @Override
    public Boolean updateCourse(int id, int cid) {
        return courseUserDao.update(id,cid)>0;
    }

    @Override
    public Boolean del(int uid) {
        return courseUserDao.del(uid)>0;
    }


}
